<template>
    <div class="module-ad-create module-ad-create--sell">
        <loading v-if="isLoading === true" style="margin-top: 64px;"></loading>
        <template v-if="isLoading === false">
            <validator :rules="rules">
                <form class="m-form-page" name="form" action="javascript:;">
                    <div class="col-row">
                        <div class="col-label">
                            <label>交易幣種</label>
                        </div>
                        <div class="col-input">
                            <select class="fn-block col-select"
                                    name="assetcode"
                                    v-model="form.assetcode">
                                <option v-for="item in assetCodeList"
                                        :value="item">{{item}}</option>
                            </select>
                            <div class="ui-tip"></div>
                        </div>
                        <!--<div class="col-tip">-->
                        <!--<span class="fn-red">*</span>-->
                        <!--</div>-->
                    </div>
                    <div class="col-row">
                        <div class="col-label">
                            <label>國家</label>
                        </div>
                        <div class="col-input">
                            <select class="fn-block col-select"
                                    name="country"
                                    v-model="form.country">
                                <option v-for="item in countryList"
                                        :value="item">{{item}}</option>
                            </select>
                            <div class="ui-tip"></div>
                        </div>
                    </div>
                    <div class="col-row">
                        <div class="col-label">
                            <label>貨幣</label>
                        </div>
                        <div class="col-input">
                            <select class="fn-block col-select"
                                    name="currency"
                                    v-model="form.currency">
                                <option value="CNY">CNY</option>
                            </select>
                            <div class="ui-tip"></div>
                        </div>
                    </div>
                    <div class="col-row">
                        <div class="col-label">
                            <label>交易價格</label>
                        </div>
                        <div class="col-input col-input--unit">
                            <em class="unit">CNY</em>
                            <input type="text"
                                   name="tradePrice"
                                   class="input fn-block"
                                   maxlength="11"
                                   v-number="{model: 'form.tradePrice', precision: 2}"
                                   autocomplete="off"
                                   :placeholder="rules.tradePrice.requiredTip"
                                   v-model="form.tradePrice">
                            <div class="ui-tip"></div>
                        </div>
                        <div class="col-suffix">市場參考價格： <em class="strong">{{marketPrice}}</em> CNY</div>
                    </div>
                    <div class="col-row" style="margin-bottom: 0;">
                        <div class="col-label">
                            <label>付款方式</label>
                        </div>
                        <div class="col-input" style="width: 800px;">
                            <label>
                                <input type="checkbox"
                                       name="payTypeAlipay"
                                       @change="changePayType('payTypeAlipay')"
                                       v-model="payTypeAlipay"/>
                                <span class="text">支付寶</span>
                            </label>
                            <span class="text" style="margin-left: 8px;">
                            <template v-if="alipayInfo&&alipayInfo.alipayNo">
                                <span >{{alipayInfo.name}}&nbsp;&nbsp;{{format.getEncryptedText(alipayInfo.alipayNo)}}</span>&nbsp;&nbsp;
                                <a href="javascript:;" class="link" @click="doAlipay('MOD')">修改</a>
                            </template>
                            <span v-if="alipayInfo&&!alipayInfo.alipayNo"><a @click="doAlipay('ADD')" href="javascript:;">添加</a></span>
                        </span>
                        </div>
                    </div>
                    <div class="col-row">
                        <div class="col-label">
                            <label>&nbsp;</label>
                        </div>
                        <div class="col-input" style="width: 800px;">
                            <label>
                                <input type="checkbox"
                                       @change="changePayType('payTypeBank')"
                                       name="payTypeBank"
                                       v-model="payTypeBank">
                                <span class="text">銀行卡</span>
                            </label>
                            <span class="text" style="margin-left: 8px;">
                            <template v-if="bankInfo&&bankInfo.acnumber">
                                <span>{{bankInfo.name}}&nbsp;&nbsp;{{bankInfo.bank}}&nbsp;&nbsp;{{format.getSuffixBank(bankInfo.acnumber)}}</span>&nbsp;&nbsp;
                                <a href="javascript:;" class="link" @click="doBank('MOD')">修改</a>
                            </template>
                            <span v-if="bankInfo&&!bankInfo.acnumber"><a @click="doBank('ADD')" href="javascript:;">添加</a></span>
                        </span>
                            <div class="ui-tip" ref="checkboxPayType"></div>
                        </div>
                        <input type="hidden" v-model="form.payType">
                    </div>
                    <div class="col-row">
                        <div class="col-label">
                            <label>最小售出個數</label>
                        </div>
                        <div class="col-input col-input--unit">
                            <em class="unit">{{form.assetcode}}</em>
                            <input type="text"
                                   name="minAmount"
                                   class="input fn-block"
                                   v-number="{model: 'form.minAmount', precision: 4}"
                                   maxlength="11"
                                   autocomplete="off"
                                   :placeholder="rules.minAmount.requiredTip"
                                   v-model="form.minAmount">
                            <div class="ui-tip"></div>
                        </div>
                    </div>
                    <div class="col-row">
                        <div class="col-label">
                            <label>最大售出個數</label>
                        </div>
                        <div class="col-input col-input--unit">
                            <em class="unit">{{form.assetcode}}</em>
                            <input type="text"
                                   name="maxAmount"
                                   class="input fn-block"
                                   v-number="{model: 'form.maxAmount', precision: 4}"
                                   maxlength="11"
                                   autocomplete="off"
                                   :placeholder="rules.maxAmount.requiredTip"
                                   v-model="form.maxAmount">
                            <div class="ui-tip" ref="maxAmount"></div>
                        </div>
                    </div>
                    <div class="col-row">
                        <div class="col-label">
                            <label>備註信息</label>
                        </div>
                        <div class="col-input">
                        <textarea name="remark"
                                  class="input fn-block"
                                  autocomplete="off"
                                  maxlength="120"
                                  placeholder="可在備註信息中填寫您對買方的要求，如在線時間等（選填）"
                                  v-model="form.remark"
                                  rows="5"></textarea>
                            <div class="ui-tip"></div>
                        </div>
                    </div>
                    <div class="col-row">
                        <div class="col-label">
                            <label for="payPwd">資金密碼</label>
                        </div>
                        <div class="col-input">
                            <input type="password"
                                   class="fn-block"
                                   autocomplete="off"
                                   id="payPwd"
                                   name="payPwd"
                                   :placeholder="rules.payPwd.requiredTip"
                                   v-model="form.payPwd">
                            <div class="ui-tip"></div>
                        </div>
                    </div>
                    <div class="col-row col-row--btns">
                        <div class="col-label">
                            <label>&nbsp;</label>
                        </div>
                        <div class="col-text">
                            <template v-if="userLevel === 'LEVEL1' || userLevel === 'LEVEL2'">
                                <button type="submit"
                                        class="ui-btn"
                                        v-if="isRequesting === false"
                                        @click="submit()">發佈
                                </button>
                                <button type="submit"
                                        class="ui-btn"
                                        disabled
                                        v-if="isRequesting === true">操作中...
                                </button>
                            </template>
                            <template  v-if="userLevel === 'LEVEL0'">
                                <button type="submit"
                                        class="ui-btn"
                                        disabled>發佈</button>
                                <span class="fn-red" style="margin-left: 4px;">請先做KYC-1實名認證</span>
                            </template>
                        </div>
                    </div>
                </form>
            </validator>
        </template>

        <template class="conponent">
            <template v-if="isShowAlipay === true && doType === 'MOD'">
                <add-alipay type="MOD"
                            :info="alipayInfo"
                            v-on:hideDialog='isShowAlipay = false'
                            :on-success="onAddAlipaySuccess">
                </add-alipay>
            </template>
            <template v-if="isShowAlipay === true && doType === 'ADD'">
                <add-alipay type="ADD"
                            v-on:hideDialog='isShowAlipay = false'
                            :on-success="onAddAlipaySuccess">
                </add-alipay>
            </template>
            <template v-if="isShowBank === true && doType === 'MOD'">
                <add-bank-card type="MOD"
                               :info="bankInfo"
                               v-on:hideDialog='isShowBank = false'
                               :on-success="onAddBankSuccess">
                </add-bank-card>
            </template>
            <template v-if="isShowBank === true && doType === 'ADD'">
                <add-bank-card type="ADD"
                               :info="bankInfo"
                               v-on:hideDialog='isShowBank = false'
                               :on-success="onAddBankSuccess">
                </add-bank-card>
            </template>
        </template>

        <set-phone v-if="isSettingPhone"
                   v-on:hide="isSettingPhone = false"
                   v-on:success="onSetPhoneSuccess"></set-phone>

        <set-nickname v-if="isSettingNickname"
                      v-on:success="onSetNickNameSuccess"
                      v-on:hide="isSettingNickname = false"></set-nickname>


        <ad-success-dialog v-if="showDialog" v-on:hide="hideDialog"></ad-success-dialog>
    </div>
</template>

<script type="text/babel">
    import Validator from '../../../../../grsc-base/component/Validator/main';
    import Loading from '../../../../../grsc-base/component/Loading.vue';
    import lib from '../../../../common/lib';
    import format from '../../../../common/format';
    import commonService from '../../../../common/commonService';
    import AddAlipay from '../../../../component/addAlipay/addAlipay';
    import AddBankCard from '../../../../component/addBankCard/addBankCard';
    import {PAY_TYPE_BANK, PAY_TYPE_ALIPAY} from '../../../../common/contants';
    import setNickname from '../../../../component/setNickName.vue';
    import setPhone from '../../../../component/setPhone.vue';
    import adSuccessDialog from '../../ad/component/adSuccessDialog.vue';
    import config from '../../config';
    import service from '../service';

    export default {
        components: {
            Loading,
            Validator,
            AddAlipay,
            AddBankCard,
            setNickname,
            setPhone,
            adSuccessDialog
        },
        computed: {
            userLevel() {
                return this.level;
            }
        },
        data() {
            let doType = config.DO_TYPE_CREATE;
            if (this.$route.params.advertId) {
                doType = config.DO_TYPE_UPDATE;
            }

            return {
                isLoading: true,
                config: config,
                format,
                doType: doType,
                isSettingNickname: false,
                isSettingPhone:false,
                showDialog:false,
                assetCodeList: [],
                countryList:[],
                alipayInfo: null,
                bankInfo: null,
                isRequesting: false,
                payTypeAlipay: false,
                payTypeBank: false,

                // 总资产
                assets: {},
                form: {
                    assetcode: config.DEFAULT_ASSET_CODE,
                    country: '中國',
                    currency: 'CNY',
                    tradePrice: '',
                    payType: '',
                    minAmount: '',
                    maxAmount: '',
                    remark: '',
                    payPwd: ''
                },
                rules: {
                    tradePrice: {
                        required: true,
                        requiredTip: '請輸入交易價格',
                        min: 0,
                        minTip: '請輸入大於0的價格'
                    },
                    minAmount: {
                        required: true,
                        requiredTip: '請輸入最小售出個數',
                        min: 0.01,
                        minTip: '請輸入大於0.01的個數'
                    },
                    maxAmount: {
                        tip: '您的資產餘額：--',
                        required: true,
                        requiredTip: '請輸入最大售出個數',
                        min: 0.01,
                        minTip: '請輸入大於0.01的個數',
                        max: '--',
                        maxTip: '超過了您的可用資產'
                    },
                    remark: {
                        maxlength: '120',
                        maxlengthTip: '最多輸入120個字符'
                    },
                    payPwd: {
                        required: true,
                        requiredTip: '請輸入資金密碼'
                    }
                },
                marketPrice: '--',

                isShowAlipay: false,
                isShowBank: false,
            };
        },
        watch: {
            payTypeAlipay(newVal, oldVal) {
                this._setPayType();
            },
            payTypeBank(newVal, oldVal) {
                this._setPayType();
            },
            'form.assetcode'(newVal, oldVal) {
                this._fetchCurrentPrice();
                this._setBalance();
            },
            level(newVal, oldVal) {

            },
        },
        props: {
            level: {
                type: String,
                default: 'LEVEL1'
            },
            nickName: {
                type: String,
                default: ''
            }
        },
        created(){
            this._fetchCurrentPrice();
            this._fetchInitInfo();
        },
        methods: {

            onSetNickNameSuccess() {
                this.isSettingNickname = false;
                this.submit();
            },

            onSetPhoneSuccess(){
                this.isSettingPhone = false;
                this.submit();
            },

            hideDialog(){
                this.showDialog = false;
            },

            /**
             * 设置可用余额
             */
            _setBalance() {
                let precision = this.$$c2cCoin[this.form.assetcode].amountPrecision;
                let max = this.assets[this.form.assetcode].amountAvailable;
                this.rules.maxAmount.max = max;
                this.rules.maxAmount.tip = '您的資產餘額：' + this.$$filter.floorFix(max, precision) + this.form.assetcode;
                $(this.$refs.maxAmount).html('<span class="text">' + this.rules.maxAmount.tip + '</span>');
            },

            _fetchInitInfo() {
                let that = this;
                this.isLoading = true;
                if (this.doType === config.DO_TYPE_CREATE) {
                    $.when(service.getSellInfo(), commonService.getTotalAssets()).done((infoRep, assetsRep) => {
                        this.isLoading = false;
                        dealInfoRep(infoRep);
                        dealAssetsRep(assetsRep);
                    });
                } else {
                    $.when(service.getSellInfo(), service.sellDetailEdit({
                        advertId: this.$route.params.advertId
                    }), commonService.getTotalAssets()).done((infoRep, detailRep, assetsRep) => {
                        this.isLoading = false;
                        dealInfoRep(infoRep);
                        dealDetailRep(detailRep);
                        dealAssetsRep(assetsRep);
                    })
                }

                function dealInfoRep(rep) {
                    let data;
                    if (rep.code === window.CODE.SUCCESS) {
                        data = rep.data;
                        that.assetCodeList = data.assetcodeList;
                        that.countryList = data.countryList;

                        let list = rep.data.c2cBasePayChannelDto;
                        if (list.length !== 0) {
                            $.map(list, (item, index) => {
                                if (item.c2cPayType === PAY_TYPE_ALIPAY) {
                                    that.alipayInfo = item;
                                }
                                if (item.c2cPayType === PAY_TYPE_BANK) {
                                    that.bankInfo = item;
                                }
                            });
                        }
                    }
                }

                function dealDetailRep(rep) {
                    if (rep.code === window.CODE.SUCCESS) {
                        let data = rep.data;
                        that.form.assetcode = data.assetcode;
                        that.form.country = data.country;
                        that.form.currency = data.currency;
                        that.form.tradePrice = data.tradePrice;
                        that.form.payType = data.payType;
                        that.form.minAmount = data.minAmount;
                        that.form.maxAmount = data.maxAmount;
                        that.form.remark = data.remark;
                        $.map(that.form.payType, (item, index) => {
                            if (item === PAY_TYPE_ALIPAY) {
                                that.payTypeAlipay = true;
                            }
                            if (item === PAY_TYPE_BANK) {
                                that.payTypeBank = true;
                            }
                        });
//                    } else if (rep.code === window.CODE.ADVERT_HAS_INVALID.CODE) {
//                        window.alert({
//                            content: window.CODE.ADVERT_HAS_INVALID[that.$i18n.locale],
//                            btnText: '我的廣告'
//                        }).done(() => {
//                            window.location.href = './c2c.html#/order/advert';
//                        });
//                    } else if (rep.code === window.CODE.REQUEST_ERROR.CODE) {
//                        window.alert({
//                            content: rep.msg,
//                            btnText: '我的廣告'
//                        }).done(() => {
//                            window.location.href = './c2c.html#/order/advert';
//                        });
                    } else {
                        window.alert({
                            content: rep.msg,
                            btnText: '我的廣告'
                        }).done(() => {
                            window.location.href = './c2c.html#/order/advert';
                        });
                    }
                }

                function dealAssetsRep(rep) {
                    if (rep.code === window.CODE.SUCCESS) {
                        rep.data.forEach(item=>{
                            that.assets[item.assetCode] = item;
                        });
                        that._setBalance();
                    } else if(rep.code === window.CODE.NO_PERMISSION.CODE ){
                        let from = window.encodeURIComponent(window.location.href);
                        window.location.href = './login.html?from=' + from;
                    } else{
                        window.error(rep.msg);
                    }
                }

            },

            _fetchCurrentPrice() {
                lib.getCurrentPriceByCoin(this.form.assetcode, (repData) => {
                    this.marketPrice = repData.priceCNY;
                });
            },

            changePayType(type) {
                if (type === 'payTypeAlipay' && this.payTypeAlipay) {
                    this.payTypeBank = false
                }
                if (type === 'payTypeBank' && this.payTypeBank) {
                    this.payTypeAlipay = false
                }
                let $checkboxTip = $(this.$refs.checkboxPayType);
                $checkboxTip.html('');
            },

            _setPayType() {
                if (this.payTypeAlipay && this.payTypeBank) {
                    this.form.payType = [config.PAY_TYPE_ALIPAY, config.PAY_TYPE_BANK];
                } else if (this.payTypeAlipay === true && this.payTypeBank === false) {
                    this.form.payType = [config.PAY_TYPE_ALIPAY];
                } else if (this.payTypeAlipay === false && this.payTypeBank === true) {
                    this.form.payType = [config.PAY_TYPE_BANK];
                } else {
                    this.form.payType = '';
                }
            },

            /**
             * 发布
             */
            submit() {
                let $payType = $(this.$refs.checkboxPayType);

                let flagForm = this.rules.$checkAll();
                let flagPayType = true;

                if (this.payTypeAlipay === false && this.payTypeBank === false) {
                    flagPayType = false;
                    $payType.html('<span class="error">請選擇付款方式</span>');
                } else if (this.payTypeAlipay === true && !(this.alipayInfo && this.alipayInfo.alipayNo)) {   // 選擇阿里支付
                    flagPayType = false;
                    $payType.html('<span class="error">請設置付款方式</span>');
                } else if (this.payTypeBank === true && !(this.bankInfo && this.bankInfo.acnumber)) {   // 選擇銀行卡
                    flagPayType = false;
                    $payType.html('<span class="error">請設置付款方式</span>');
                } else {
                    this.changePayType();
                }

                if (flagForm === false || flagPayType === false) {
                    return;
                }

                let header = {
                    'pay-password': this.form.payPwd
                };

                let param = {
                    assetcode: this.form.assetcode,
                    country: this.form.country,
                    currency: this.form.currency,
                    tradePrice: this.form.tradePrice,
                    payType: this.form.payType,
                    minAmount: this.form.minAmount,
                    maxAmount: this.form.maxAmount,
                    remark: this.form.remark
                };

                this.isRequesting = true;

                if (this.doType === config.DO_TYPE_CREATE) {
                    service.createAdSell(param, header).done(rep => {
                        if (rep.code === window.CODE.SUCCESS) {
                            this.showDialog = true;
//                            window.success('操作成功', () => {
//                                window.location.href = './c2c.html';
//                            });
                        } else if (rep.code === window.CODE.PAY_PWD.CODE) {
                            let num = rep.data.num;
                            if (3 - num > 0) {
                                this.rules.payPwd.$setError(this.$t('common.IncorrectAssetPassTip',{num: 3-num}));
                            } else {
                                this.rules.payPwd.$setError(window.CODE.PAY_PWD_LOCK[this.$i18n.locale]);
                            }
                        } else if (rep.code === window.CODE.PAY_PWD_LOCK.CODE) {
                            this.rules.payPwd.$setError(window.CODE.PAY_PWD_LOCK[this.$i18n.locale]);
                        } else if( rep.code === window.CODE.NO_NICKNAME.CODE){
                            this.isSettingNickname = true;
                        } else if( rep.code === window.CODE.NO_PHONE.CODE){
                            this.isSettingPhone = true;
                        } else {
                            window.error(rep.msg);
                        }
                    }).fail((rep) => {
                        window.error(rep.msg);
                    }).always(() => {
                        this.isRequesting = false;
                    });
                } else {
                    param.advertId = this.$route.params.advertId;
                    service.updateAdSell(param, header).done(rep => {
                        if (rep.code === window.CODE.SUCCESS) {
                            window.success('操作成功', () => {
                                window.location.href = './c2c.html';
                            });
                        } else {
                            window.error(rep.msg);
                        }
                    }).fail((rep) => {
                        window.error(rep.msg);
                    }).always(() => {
                        this.isRequesting = false;
                    });
                }

            },

            /**
             * 支付寶
             */
            doAlipay(doType) {
                this.doType = doType;
                this.isShowAlipay = true;
            },

            /**
             * 銀行卡
             */
            doBank(doType) {
                this.doType = doType;
                this.isShowBank = true;
            },

            /**
             * 添加支付寶成功
             */
            onAddAlipaySuccess(info) {
                this.isShowBank = false;
                info.payType = PAY_TYPE_ALIPAY;
                this.alipayInfo = info;
            },

            /**
             * 添加銀行卡成功
             */
            onAddBankSuccess(info) {
                this.isShowBank = false;
                info.payType = PAY_TYPE_BANK;
                this.bankInfo = info;
            }
        }
    }
</script>

<style lang="sass" rel="stylesheet/scss">
    .module-ad-create--sell {

    }
</style>
